using Com.Modules.AdminModule.Services.Abstractions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;
using XiheNet;

namespace Com.Core.Module.Filters;

/// <summary>
/// JWT 授权过滤器属性，可在控制器或方法上标记
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class JwtAuthAttribute: Attribute, IAsyncAuthorizationFilter
{
    public string _userType { get; set; } = "User"; // 默认类型为 User

    /// <summary>
    /// 无参构造函数，支持依赖注入
    /// </summary>
    public JwtAuthAttribute()
    {
    }

    /// <summary>
    /// 带参构造函数，用于直接指定用户类型
    /// </summary>
    /// <param name="userType">用户类型</param>
    public JwtAuthAttribute(string UserType)
    {
        _userType = UserType;
    }

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        // 创建响应对象
        var response = new XResponse<object>();   

        // 从请求头中获取 Token
        if (!context.HttpContext.Request.Headers.TryGetValue("Token", out var tokenValues) ||
            string.IsNullOrEmpty(tokenValues.ToString()))
        {
            // 返回统一格式的错误响应，HTTP状态码保持200
            response = CreateErrorResponse("1100", "登录令牌无效");
            context.Result = new ObjectResult(response) { StatusCode = StatusCodes.Status200OK };
            return;
        }

        var token = tokenValues.ToString();
        bool isUserPass = false;
        bool isDevPass = false;
        bool isAdminPass = false;

        if (_userType.Contains("User")) { 
            // // 从DI容器中获取用户服务
            // var userService = context.HttpContext.RequestServices.GetService<IUserService>();
            // if (userService == null)
            // {
            //     response = CreateErrorResponse("1000", "系统服务错误");
            //     context.Result = new ObjectResult(response) { StatusCode = StatusCodes.Status200OK };
            //     return;
            // }

            // // 验证Token
            // var (isOk, user) = await userService.IsTokenValid(token);
            // if (isOk)
            // {
            //     // 将用户信息存储到HttpContext中，方便后续使用
            //     isUserPass = true;
            //     context.HttpContext.Items["UserType"] = "User";
            //     context.HttpContext.Items["CurrentUser"] = user;
            // }
        } else if (_userType.Contains("Developer")) {
            // // 从DI容器中获取开发商服务
            // var developerService = context.HttpContext.RequestServices.GetService<IDeveloperService>();
            // if (developerService == null)
            // {
            //     response = CreateErrorResponse("1000", "系统服务错误");
            //     context.Result = new ObjectResult(response) { StatusCode = StatusCodes.Status200OK };
            //     return;
            // }

            // // 验证Token
            // var (isOk, developer) = await developerService.IsTokenValidAsync(token);
            // if (isOk)
            // {
            //     // 将开发商信息存储到HttpContext中，方便后续使用
            //     isDevPass = true;
            //     context.HttpContext.Items["UserType"] = "Developer";
            //     context.HttpContext.Items["CurrentDeveloper"] = developer;
            // }
        } else if (_userType.Contains("Admin")) {
            // 从DI容器中获取管理员服务
            var adminService = context.HttpContext.RequestServices.GetService<IAdminService>();
            if (adminService == null)
            {
                response = CreateErrorResponse("1000", "系统服务错误");
                context.Result = new ObjectResult(response) { StatusCode = StatusCodes.Status200OK };
                return;
            }

            // 验证Token
            var (isOk, admin) = await adminService.IsTokenValid(token);
            if (isOk)
            {
                isAdminPass = true;
                context.HttpContext.Items["UserType"] = "Admin";
                context.HttpContext.Items["CurrentAdmin"] = admin;
            }
        }
        else
        {
            response = CreateErrorResponse("1000", "系统服务错误");
            context.Result = new ObjectResult(response) { StatusCode = StatusCodes.Status200OK };
            return;

        }

        if(!isUserPass && !isDevPass && !isAdminPass){
            response = CreateErrorResponse("1100", "登录令牌无效");
            context.Result = new ObjectResult(response) { StatusCode = StatusCodes.Status200OK };
            return;
        }
    }

    // 创建错误响应对象的辅助方法
    private XResponse<object> CreateErrorResponse(string code, string message)
    {
        return new XResponse<object>
        {
            RespHead = new XRespHead
            {
                Code = code,
                Message = message
            }
        };
    }
}
